package com.jz.community.moduleshopping.goodsDetail.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.bean.baseCartInfo.NewAddCartInfo;
import com.jz.community.basecomm.bean.baseGoods.BaseGoodsInfo;
import com.jz.community.basecomm.bean.basePontageInfo.BasePostageInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.AddCartTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.RxTimeTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToCartRefreshEvent;
import com.jz.community.commview.banner.Banner;
import com.jz.community.commview.banner.BannerConfig;
import com.jz.community.commview.banner.Transformer;
import com.jz.community.commview.view.EmptyInfoLayout;
import com.jz.community.commview.view.GradationScrollView;
import com.jz.community.commview.view.widget.FlowLayout;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.goodsDetail.adapter.ShopDetailAdapter;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsCouponInfo;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsDetailInfo;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsPostageInfo;
import com.jz.community.moduleshopping.goodsDetail.enums.GoodsAddCartType;
import com.jz.community.moduleshopping.goodsDetail.presenter.GoodsDetailPresenter;
import com.jz.community.moduleshopping.goodsDetail.task.GetGoodsCouponTask;
import com.jz.community.moduleshopping.goodsDetail.task.GetShopPostageTask;
import com.jz.community.moduleshopping.goodsDetail.ui.view.GoodsDetailAddCartPop;
import com.jz.community.moduleshopping.goodsDetail.ui.view.GoodsDetailCouponPop;
import com.jz.community.moduleshopping.goodsDetail.ui.view.ShareGoodsPopUp;
import com.jz.community.moduleshopping.goodsDetail.utils.BannerGlideImageLoader;
import com.jz.community.moduleshopping.orderDetail.bean.OrderEvent;
import com.jz.community.moduleshopping.shopCart.task.GetCartNunTask;
import com.jz.community.moduleshopping.shopCart.ui.ShopCartActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;
import q.rorbin.badgeview.QBadgeView;

/**
 * Created by Tony.Fan on 2018/3/27 09:29
 * 商品详情页
 */
@Route(path = RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL)
public class GoodsDetailActivity extends BaseMvpActivity<GoodsDetailView.View, GoodsDetailPresenter> implements GoodsDetailView.View, GradationScrollView.ScrollViewListener {

    @BindView(R2.id.gt_top_banner)
    Banner gtTopBanner;
    @BindView(R2.id.gt_top_banner_parent)
    RelativeLayout gtTopBannerParent;
    @BindView(R2.id.gt_top_type)
    TextView gtTopType;
    @BindView(R2.id.gt_top_name)
    TextView gtTopName;
    @BindView(R2.id.gt_top_price_r)
    TextView gtTopPriceR;
    @BindView(R2.id.gt_top_price)
    TextView gtTopPrice;
    @BindView(R2.id.gt_top_gray_r)
    TextView gtTopGrayR;
    @BindView(R2.id.gt_top_gray_price)
    TextView gtTopGrayPrice;
    @BindView(R2.id.gt_top_discount)
    TextView gtTopDiscount;
    @BindView(R2.id.gt_top_gray_ll)
    LinearLayout gtTopGrayLl;
    @BindView(R2.id.gt_top_stock)
    TextView gtTopStock;
    @BindView(R2.id.gt_top_msg_hot)
    TextView gtTopMsgHot;
    @BindView(R2.id.gt_top_msg_ll)
    LinearLayout gtTopMsgLl;
    @BindView(R2.id.gt_top_num)
    TextView gtTopNum;
    @BindView(R2.id.gt_top_sale_tv)
    TextView gtTopSaleTv;
    @BindView(R2.id.gt_top_sale_rl)
    RelativeLayout gtTopSaleRl;
    @BindView(R2.id.gt_top_second_tv)
    TextView gtTopSecondTv;
    @BindView(R2.id.gt_top_second_count)
    CountdownView gtTopSecondCount;
    @BindView(R2.id.gt_top_second_ll)
    LinearLayout gtTopSecondLl;
    @BindView(R2.id.gt_top_spec)
    TextView gtTopSpec;
    @BindView(R2.id.gt_top_spec_ll)
    LinearLayout gtTopSpecLl;
    @BindView(R2.id.gt_top_spec_line)
    ImageView gtTopSpecLine;
    @BindView(R2.id.gt_top_coupon)
    TextView gtTopCoupon;
    @BindView(R2.id.gt_top_coupon_ll)
    LinearLayout gtTopCouponLl;
    @BindView(R2.id.gt_top_coupon_line)
    ImageView gtTopCouponLine;
    @BindView(R2.id.gt_top_freight)
    TextView gtTopFreight;
    @BindView(R2.id.gt_top_right_freight)
    TextView gtTopRightFreight;
    @BindView(R2.id.gt_top_freight_ll)
    LinearLayout gtTopFreightLl;
    @BindView(R2.id.gt_top_freight_tv)
    TextView gtTopFreightTv;
    @BindView(R2.id.gt_top_freight_line)
    ImageView gtTopFreightLine;
    @BindView(R2.id.gt_top_points)
    TextView gtTopPoints;
    @BindView(R2.id.gt_top_points_ll)
    LinearLayout gtTopPointsLl;
    @BindView(R2.id.gt_top_points_line)
    ImageView gtTopPointsLine;
    @BindView(R2.id.fl_explain)
    FlowLayout gtTopExplain;
    @BindView(R2.id.gt_top_explain_ll)
    LinearLayout gtTopExplainLl;
    @BindView(R2.id.gt_top_shop_img)
    CircleImageView gtTopShopImg;
    @BindView(R2.id.gt_top_shop_name)
    TextView gtTopShopName;
    @BindView(R2.id.gt_top_shop_num)
    TextView gtTopShopNum;
    @BindView(R2.id.gt_top_shop_rv)
    RecyclerView gtTopShopRv;
    @BindView(R2.id.gt_top_shop_ll)
    LinearLayout gtTopShopLl;
    @BindView(R2.id.gt_bot_ll)
    LinearLayout gtBotLl;
    @BindView(R2.id.gt_bot_web)
    WebView gtBotWeb;
    @BindView(R2.id.gt_top_scroll)
    LinearLayout gtTopScroll;
    @BindView(R2.id.goods_detail_parent)
    GradationScrollView goodsDetailParent;
    @BindView(R2.id.goods_detail_back)
    ImageView goodsDetailBack;
    @BindView(R2.id.goods_detail_title)
    TextView goodsDetailTitle;
    @BindView(R2.id.goods_detail_toolbar)
    Toolbar goodsDetailToolbar;
    @BindView(R2.id.goods_detail_service_ll)
    LinearLayout goodsDetailServiceLl;
    @BindView(R2.id.goods_detail_cart)
    ImageView goodsDetailCart;
    @BindView(R2.id.goods_detail_cart_ll)
    LinearLayout goodsDetailCartLl;
    @BindView(R2.id.goods_detail_share_ll)
    LinearLayout goodsDetailShareLl;
    @BindView(R2.id.goods_detail_cart_add_ll)
    RelativeLayout goodsDetailCartAddLl;
    @BindView(R2.id.goods_detail_buy_tv)
    TextView goodsDetailBuyTv;
    @BindView(R2.id.goods_detail_buy_ll)
    LinearLayout goodsDetailBuyLl;
    @BindView(R2.id.goods_detail_bot_ll)
    LinearLayout goodsDetailBotLl;
    @BindView(R2.id.goods_detail_fab)
    FloatingActionButton goodsDetailFab;
    @BindView(R2.id.gt_parent)
    RelativeLayout gtParent;
    @BindView(R2.id.goods_empty_layout)
    EmptyInfoLayout goodsEmptyLayout;
    private int height;
    private ShopDetailAdapter shopAdapter;
    private QBadgeView qBadgeView;
    private GoodsDetailAddCartPop goodsDetailAddCartPop;
    private GoodsDetailInfo mGoodsDetailInfo;
    private String url; //请求地址
    private GoodsDetailCouponPop goodsDetailCouponPop;
    private GoodsCouponInfo.EmbeddedBean embeddedCouponInfo;
    private long startTime;
    private long endTime;
    private GoodsDetailInfo.SkuInfosBean skuInfos;
    private String goodsPrice;
    private String discountPrice;
    private long mCurTime;
    private ViewGroup.LayoutParams lp_banner;
    private RegionsBean.EmbeddedBean.ContentBean region;
    private int goodFrom = -1;
    private ShareGoodsPopUp shareGoodsPopUp;
    private String goodSpStr;

    private int ADD_GOODS_CART_REQUESR_CODE = 1;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_goods_detail;
    }

    @Override
    protected void initDatas() {
        region = BaseSpUtils.getInstance().getRegion(getContext());
        setGoodsBannerParams();
        getIntents();
        getGoodsDetailData();
        initListeners();
        registerOrderEvent();
    }

    private void setGoodsBannerParams() {
        ImmersionBar.with(this).statusBarColor(R.color.white).fitsSystemWindows(true).statusBarDarkFont(true, 0.2f).init();
        lp_banner = gtTopBanner.getLayoutParams();
        lp_banner.height = SHelper.getScrrenWidth(this);
        gtTopBanner.setLayoutParams(lp_banner);
        qBadgeView = new QBadgeView(this);
        goodsDetailAddCartPop = new GoodsDetailAddCartPop(this);
    }

    @Override
    protected GoodsDetailPresenter createPresenter() {
        return new GoodsDetailPresenter(this);
    }

    private void getIntents() {
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        if (intent.hasExtra("goodFrom")) {
            goodFrom = intent.getIntExtra("goodFrom", -1);
            handleGoodsDetailFrom(intent.getIntExtra("goodFrom", -1));
        }
    }

    /**
     * 不同来源UI展示
     *
     * @param goodFrom
     */
    private void handleGoodsDetailFrom(int goodFrom) {
        switch (goodFrom) {
            case 0:
                SHelper.gone(goodsDetailCartAddLl);
                break;
        }
    }

    /**
     * 指定自提点商品
     */
    private void handleGoodsPoint() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getPickupPoint())) {
            SHelper.gone(goodsDetailCartAddLl);
            if (goodsDetailAddCartPop != null) {
                goodsDetailAddCartPop.setShowType(GoodsAddCartType.TYPE_2.getType());
            }
        }
    }

    /**
     * 指定365商品
     */
    private void handleSourceGoods() {
        if (mGoodsDetailInfo.getSource() == 3) {
            SHelper.gone(goodsDetailCartAddLl);
            if (goodsDetailAddCartPop != null) {
                goodsDetailAddCartPop.setShowType(GoodsAddCartType.TYPE_2.getType());
            }
        }
    }

    /**
     * 订单列表
     */
    @SuppressLint("CheckResult")
    private void registerOrderEvent() {
        RxBus.getInstance().register(OrderEvent.toOrderRxBusTag, OrderEvent.class).subscribe(new Consumer<OrderEvent>() {
            @Override
            public void accept(OrderEvent orderEvent) throws Exception {
                if (orderEvent.getOrderType() == OrderEvent.ORDER_TYPE_1) {
                    finish();
                }
            }
        });
    }

    /**
     * 加载商品详情页基础信息
     *
     * @param goodsDetailInfo
     */
    private void loadGoodsDetail(GoodsDetailInfo goodsDetailInfo) {
        mGoodsDetailInfo = goodsDetailInfo;
        SHelper.vis(gtBotLl, gtParent);
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.get_embedded())) {
            mPresenter.getShopGoodsInfo("0", goodsDetailInfo.getShop().getId());
            getSkuInfo();
            handleGoodsSpecial();
            getGoodsCouponTask();
            getPostageInfo(region.getCode());
            loadGoodsBanner();
            loadGoodsDetailInfo();
            loadWebData();
            handleGoodsSku();
            handleGoodsPoint();
            handleSourceGoods();
            handleBuyGoodsNum();
            handleShowGoodsInfoMsg();
            showGoodsExplain();
            showGoodsTags();
            addGoodsSkuInfo();
            loadCartNum();
        } else {
            SHelper.vis(goodsEmptyLayout);
        }
    }

    private void getGoodsDetailData() {
        mPresenter.getGoodsDetailInfo(url);
    }

    /**
     * 加载商品轮播图
     */
    private void loadGoodsBanner() {
        List<String> banner_list = mGoodsDetailInfo.getImage();
        gtTopBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        gtTopBanner.setImageLoader(new BannerGlideImageLoader());
        gtTopBanner.setImages(banner_list);
        gtTopBanner.setBannerAnimation(Transformer.Default);
        gtTopBanner.isAutoPlay(false);
        gtTopBanner.setDelayTime(5000);
        gtTopBanner.setIndicatorGravity(BannerConfig.RIGHT);
        gtTopBanner.start();
    }

    /**
     * 加载URL
     */
    private void loadWebData() {
        gtBotWeb.setFocusable(false);
        gtBotWeb.loadUrl(mGoodsDetailInfo.getLinks().getContent().getHref());
    }

    //库存
    private void handleGoodsSku() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getSkuInfos())) {
            if (calculateGoodsTotalStock(mGoodsDetailInfo) > 0) {
                gtTopStock.setText("库存充足");
            } else {
                gtTopStock.setText("库存不足");
                setBuyBtnState(false, R.color.gray_light, "已售罄");
                SHelper.gone(goodsDetailCartAddLl);
            }
        }
    }

    /**
     * 计算商品总库存
     *
     * @return
     */
    public int calculateGoodsTotalStock(GoodsDetailInfo mGoodsDetailInfo) {
        int totalGoodsStock = 0;
        for (GoodsDetailInfo.SkuInfosBean skuInfos : mGoodsDetailInfo.getSkuInfos()) {
            totalGoodsStock += ConverterUtils.toInt(skuInfos.getStock());
        }
        return totalGoodsStock;
    }

    private void handleShowGoodsInfoMsg() {
        SHelper.vis(gtTopSpecLl, gtTopExplainLl, gtTopSpecLine);
        gtTopSpec.setText("请选择规格");
    }

    /**
     * 更新选中商品规格
     *
     * @param spStr
     */
    public void updateGoodsSkuProperties(String spStr) {
        goodSpStr = spStr;
        if (!Preconditions.isNullOrEmpty(gtTopSpec) && goodsDetailAddCartPop.isShowing()) {
            gtTopSpec.setText(spStr);
        }
    }

    //商品店铺类型
    private void showShopType(String shopTypeId) {
        if (AppConstants.SHOP_TYPE_ID.equals(shopTypeId)) {
            SHelper.vis(gtTopType);
        } else {
            SHelper.gone(gtTopType);
        }
    }

    //购买方式(0现货 、1预售 、2折扣 、3 限时购,4 积分)
    private void handleGoodsSpecial() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getBuyType())) {
            switch (mGoodsDetailInfo.getBuyType()) {
                case 0:
                    showBuyTypePrice(0);
                    break;
                case 1:
                    showBuyTypePrice(1);
                    handleSaleStartTime();
                    break;
                case 2:
                    showBuyTypePrice(2);
                    break;
                case 3:
                    showBuyTypePrice(3);
                    buyGoodsTimes();
                    break;
                case 4:
                    showBuyTypePrice(4);
                    break;
                default:
                    break;
            }
        } else {
            SHelper.invis(gtTopMsgLl);
        }
    }

    /**
     * 预售发货时间
     */
    private void handleSaleStartTime() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getSaleStartTime())) {
            gtTopSaleTv.setText("预计" + mGoodsDetailInfo.getSaleStartTime() + "发货");
            SHelper.vis(gtTopSaleRl);
        }
    }

    /**
     * 积分状态
     */
    private void handleIntegralState() {
        setBuyBtnState(true, R.drawable.btn_buy_shopping_btn, "立即兑换");
    }

    /**
     * 判断用户积分
     *
     * @return
     */
    private boolean isUserIntegral() {
        double integralNum = BaseSpUtils.getInstance().getIntegralNum(this);
        if (ConverterUtils.toDouble(integralNum) >= ConverterUtils.toDouble(goodsPrice)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取SkuInfo
     *
     * @return
     */
    private void getSkuInfo() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getSkuInfos())) {
            skuInfos = mGoodsDetailInfo.getSkuInfos().get(0);
        }
    }

    /**
     * 显示购买类型价格
     *
     * @param buyType
     */
    private void showBuyTypePrice(int buyType) {
        switch (buyType) {
            case 4:
                setPrice(false);
                handleIntegralState();
                break;
            default:
                setPrice(true);
        }
    }

    /**
     * 设置显示折扣价格
     *
     * @param isBuyType
     */
    private void setPrice(boolean isBuyType) {
        SHelper.vis(gtTopGrayLl, gtTopPriceR, gtTopGrayPrice, gtTopPrice);
        if (!Preconditions.isNullOrEmpty(skuInfos.getDiscountPrice())) {
            if (isBuyType) {
                gtTopPrice.setText(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(skuInfos.getDiscountPrice())));
                discountPrice = skuInfos.getDiscountPrice();
                goodsPrice = skuInfos.getPrice();
                setStrikeThrough(goodsPrice);
            } else {
                SHelper.gone(gtTopPriceR, goodsDetailCartAddLl);
                gtTopPrice.setText(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(skuInfos.getDiscountPrice())) + "积分");
                discountPrice = skuInfos.getDiscountPrice();
                goodsPrice = skuInfos.getPrice();
                setStrikeThrough(goodsPrice);
            }
        } else {
            gtTopPrice.setText(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(skuInfos.getPrice())));
            goodsPrice = skuInfos.getPrice();
            SHelper.gone(gtTopGrayR, gtTopGrayPrice);
        }
    }

    /**
     * 设置活动价设置删除线
     *
     * @param price
     */
    private void setStrikeThrough(String price) {
        RxTextTool.getBuilder("").append(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(price))).setStrikethrough().into(gtTopGrayPrice);
    }

    //商品购买数量、积分
    private void handleBuyGoodsNum() {
        gtTopNum.setText(mGoodsDetailInfo.getSaleCount() + "位邻居已购买");
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getIntegral())) {
            gtTopPoints.setText("购买最高可获得" + mGoodsDetailInfo.getIntegral() + "积分");
            SHelper.vis(gtTopPointsLl, gtTopPointsLine);
        } else {
            SHelper.gone(gtTopPointsLl, gtTopPointsLine);
        }
    }

    /**
     * 限时购开抢状态
     */
    private void buyGoodsTimes() {
        switch (buyTimes()) {
            case 1:
                gtTopSecondTv.setText("距离开抢仅剩:");
                setBuyTimes((startTime - mCurTime), false, R.color.gray_light, "即将开抢");
                SHelper.gone(goodsDetailCartAddLl);
                SHelper.vis(gtTopSecondLl);
                break;
            case 2:
                setBuyTimes(0, false, R.color.gray_light, "活动结束");
                gtTopSecondTv.setText("抢购结束");
                SHelper.gone(goodsDetailCartAddLl, gtTopSecondCount);
                SHelper.vis(gtTopSecondLl);
                break;
            case 3:
                gtTopSecondTv.setText("距离结束还剩:");
                setBuyTimes((endTime - mCurTime), true, R.drawable.btn_buy_shopping_btn, "立即抢购");
                SHelper.gone(goodsDetailCartAddLl);
                SHelper.vis(gtTopSecondLl);
                break;
        }
    }

    /**
     * 设置倒计时
     *
     * @param isEnabled
     * @param btnCartBg
     */
    private void setBuyTimes(long time, boolean isEnabled, int btnCartBg, String buyText) {
        gtTopSecondCount.start(time);
        setBuyBtnState(isEnabled, btnCartBg, buyText);
        SHelper.gone(gtTopCouponLl, gtTopCouponLine);
        gtTopSecondCount.setOnCountdownEndListener(cv -> getGoodsDetailData());
    }

    /**
     * 设置btn背景、状态
     *
     * @param isEnabled
     * @param btnCartBg
     * @param buyText
     */
    private void setBuyBtnState(boolean isEnabled, int btnCartBg, String buyText) {
        goodsDetailBuyLl.setEnabled(isEnabled);
        goodsDetailBuyLl.setBackgroundResource(btnCartBg);
        goodsDetailBuyTv.setText(buyText);
    }

    /**
     * 限时购状态
     *
     * @return
     */
    private int buyTimes() {
        mCurTime = RxTimeTool.string2Milliseconds(mGoodsDetailInfo.getCurrentTime());
        startTime = RxTimeTool.string2Milliseconds(mGoodsDetailInfo.getLimitedStartTime());
        endTime = RxTimeTool.string2Milliseconds(mGoodsDetailInfo.getLimitedStopTime());
        if (mCurTime < startTime) {
            //未开抢
            return 1;
        } else if (mCurTime > endTime) {
            //已结束
            return 2;
        } else {
            //开抢中
            return 3;
        }
    }

    //显示商品说明
    private void showGoodsExplain() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo) && !Preconditions.isNullOrEmpty(mGoodsDetailInfo.getAssuranceServices())) {
            SHelper.vis(gtTopExplainLl);
            loadGoodsExplain(mGoodsDetailInfo.getAssuranceServices());
        } else {
            SHelper.gone(gtTopExplainLl);
        }
    }

    //显示商品标签
    private void showGoodsTags() {
        if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getTags())) {
            SHelper.vis(gtTopMsgLl);
            loadGoodsTags();
        } else {
            SHelper.gone(gtTopMsgLl);
        }
    }

    /**
     * 加载商品保障信息
     */
    private void loadGoodsExplain(List<GoodsDetailInfo.AssuranceServicesBean> assuranceServicesBeans) {
        if (!Preconditions.isNullOrEmpty(assuranceServicesBeans)) {
            TextView tv = createTextView(goodsServiceStr(assuranceServicesBeans), false);
            gtTopExplain.addView(tv);
        }
    }

    /**
     * 详情说明
     *
     * @return
     */
    private String goodsServiceStr(List<GoodsDetailInfo.AssuranceServicesBean> assuranceServicesBeans) {
        StringBuilder builder = new StringBuilder();
        for (GoodsDetailInfo.AssuranceServicesBean assuranceServicesBean : assuranceServicesBeans) {
            builder.append(assuranceServicesBean.getName());
            builder.append(",");
        }
        if (!Preconditions.isNullOrEmpty(builder)) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    /**
     * 加载商品标签信息
     */
    private void loadGoodsTags() {
        for (String goodsTag : mGoodsDetailInfo.getTags()) {
            TextView tv = createTextView(goodsTag, true);
            gtTopMsgLl.addView(tv);
        }
    }

    /**
     * 显示商品说明
     *
     * @param tvName
     * @return
     */
    public TextView createTextView(String tvName, boolean isTvBg) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv = new TextView(this);
        tv.setLayoutParams(lp);
        lp.leftMargin = SHelper.dp2px(this, 5);
        tv.setTextSize(13);
        if (isTvBg) {
            tv.setGravity(Gravity.CENTER);
            tv.setPadding(SHelper.dp2px(this, 5), 0, SHelper.dp2px(this, 5), 0);
            tv.setBackgroundResource(R.drawable.tv_border_gt);
            tv.setTextColor(ContextCompat.getColor(this, R.color.white));
        }
        tv.setText(tvName);
        return tv;
    }

    //选择规格
    @OnClick(R2.id.gt_top_spec_ll)
    void choiceSpaceOnClick() {
        if (BaseUserUtils.showIsLoginDialog(this)) {

            //已售罄
            if (calculateGoodsTotalStock(mGoodsDetailInfo) <= 0) {
                addCartPopWindow(GoodsAddCartType.TYPE_6.getType());
                return;
            }

            //限时购
            if (mGoodsDetailInfo.getBuyType() == 3) {
                goodsDetailAddCartPop.setBuyTimes(buyTimes());
                addCartPopWindow(GoodsAddCartType.TYPE_5.getType());
                return;
            }

            //指定商品自提
            if (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getPickupPoint())) {
                addCartPopWindow(GoodsAddCartType.TYPE_2.getType());
                return;
            }
        }

        //365商品
        if (mGoodsDetailInfo.getSource() == 3) {
            addCartPopWindow(GoodsAddCartType.TYPE_2.getType());
            return;
        }

        //卡包来源
        if (goodFrom == 0) {
            addCartPopWindow(GoodsAddCartType.TYPE_2.getType());
            return;
        }

        //积分兑换
        if (mGoodsDetailInfo.getBuyType() == 4) {
            if (isUserIntegral()) {
                addCartPopWindow(GoodsAddCartType.TYPE_4.getType());
            } else {
                WpToast.l(this, "积分不足");
            }
            return;
        }

        //现货、折扣 、预售
        if (mGoodsDetailInfo.getBuyType() != 4) {
            addCartPopWindow(GoodsAddCartType.TYPE_1.getType());
            return;
        }

    }

    //返回
    @OnClick(R2.id.goods_detail_back)
    void backOnClick() {
        finish();
    }

    //客服
    @OnClick(R2.id.goods_detail_service_ll)
    void serviceOnClick() {
        startActivity(new Intent(this, BaseX5WebActivity.class)
                .putExtra("url", Constant.CUSTOM_SERVICE_URL)
                .putExtra("title", "在线客服"));
    }

    //购物车
    @OnClick(R2.id.goods_detail_cart_ll)
    void cartOnClick() {
        if (BaseUserUtils.showIsLoginDialog(this)) {
            startActivityForResult(new Intent(GoodsDetailActivity.this, ShopCartActivity.class), ADD_GOODS_CART_REQUESR_CODE);
        }
    }

    //立即购买
    @OnClick(R2.id.goods_detail_buy_ll)
    void buyOnClick() {
        if (BaseUserUtils.showIsLoginDialog(this)) {
            if (mGoodsDetailInfo.getBuyType() == 4) {
                if (isUserIntegral()) {
                    addCartPopWindow(GoodsAddCartType.TYPE_4.getType());
                } else {
                    WpToast.l(this, "积分不足");
                }
            } else {
                addCartPopWindow(GoodsAddCartType.TYPE_2.getType());
            }
        }
    }

    //分享
    @OnClick(R2.id.goods_detail_share_ll)
    void shareOnClick() {
        showShareGoodsPop();
    }

    //添加购物车
    @OnClick(R2.id.goods_detail_cart_add_ll)
    void addCartOnClick() {
        if (BaseUserUtils.showIsLoginDialog(this)) {
            addCartPopWindow(GoodsAddCartType.TYPE_3.getType());
        }
    }

    //领卷
    @OnClick(R2.id.gt_top_coupon_ll)
    void goodsDetailCouponOnClick() {
        goodsCouponPop();
    }

    //返回顶部
    @OnClick(R2.id.goods_detail_fab)
    void boTopOnClick() {
        goodsDetailParent.smoothScrollTo(0, 0);
    }

    /**
     * 优惠卷
     */
    private void goodsCouponPop() {
        if (!Preconditions.isNullOrEmpty(goodsDetailCouponPop)) {
            goodsDetailCouponPop.addCouponInfos(embeddedCouponInfo.getContent());
        }
    }

    /**
     * 获取商品可领取优惠券
     */
    private void getGoodsCouponTask() {
        if (BaseUserUtils.getIsLogin(this) && !Preconditions.isNullOrEmpty(mGoodsDetailInfo.get_embedded().getCategory())) {
            new GetGoodsCouponTask(this, new ITaskCallbackListener() {
                @Override
                public void doTaskComplete(Object o) {
                    GoodsCouponInfo goodsCouponInfo = (GoodsCouponInfo) o;
                    if (!Preconditions.isNullOrEmpty(goodsCouponInfo)) {
                        loadGoodsCoupon(goodsCouponInfo);
                    }
                }
            }).execute(mGoodsDetailInfo.getShop().getId(), mGoodsDetailInfo.getId(), mGoodsDetailInfo.get_embedded().getCategory().getId());
        }
    }

    /**
     * 加载商品优惠券
     *
     * @param goodsCouponInfo
     */
    private void loadGoodsCoupon(GoodsCouponInfo goodsCouponInfo) {
        embeddedCouponInfo = goodsCouponInfo.get_embedded();
        if (!Preconditions.isNullOrEmpty(embeddedCouponInfo)) {
            SHelper.vis(gtTopCouponLl, gtTopCouponLine);
            gtTopCoupon.setText(embeddedCouponInfo.getContent().get(0).getCouponName());
            goodsDetailCouponPop = new GoodsDetailCouponPop(this);
        } else {
            SHelper.gone(gtTopCouponLl, gtTopCouponLine);
        }
    }

    private void loadGoodsDetailInfo() {
        SHelper.vis(goodsDetailBotLl);
        gtTopName.setText(mGoodsDetailInfo.getTitle());
    }

    @Override
    public void showGoodsDetailInfo(GoodsDetailInfo goodsDetailInfo) {
        loadGoodsDetail(goodsDetailInfo);
    }

    @Override
    public void showDetailShopInfo(BaseGoodsInfo shopGoodsInfo) {
        handleBindShopAdapter(shopGoodsInfo);
    }

    /**
     * 获取邮费对象
     */
    private void getPostageInfo(String cityCode) {

        //自营商品且指定自提商品
        if (AppConstants.SHOP_TYPE_ID.equals(mGoodsDetailInfo.getShop().getShopTypeId()) && (!Preconditions.isNullOrEmpty(mGoodsDetailInfo.getPickupPoint()))) {
            return;
        }

        new GetShopPostageTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                GoodsPostageInfo goodsPostageInfo = (GoodsPostageInfo) o;
                if (!Preconditions.isNullOrEmpty(goodsPostageInfo)) {
                    handleGoodsPostage(goodsPostageInfo);
                }
            }
        }).execute(mGoodsDetailInfo.getShop().getId(), cityCode);
    }

    /**
     * 邮费
     *
     * @param goodsPostageInfo
     */
    private void handleGoodsPostage(GoodsPostageInfo goodsPostageInfo) {
        GoodsPostageInfo.EmbeddedBeanXX embeddedBean = goodsPostageInfo.get_embedded();
        if (!Preconditions.isNullOrEmpty(embeddedBean) && !Preconditions.isNullOrEmpty(embeddedBean.getContent())) {
            SHelper.vis(gtTopFreightTv, gtTopFreightLl, gtTopFreightLine);
            for (BasePostageInfo basePostageInfo : embeddedBean.getContent()) {
                calculateGoodsPostageShow(basePostageInfo);
            }
        } else {
            SHelper.gone(gtTopFreightTv, gtTopFreightLl, gtTopFreightLine);
        }
    }

    /**
     * 计算限时邮费
     *
     * @param basePostageInfo
     */
    public void calculateGoodsPostageShow(BasePostageInfo basePostageInfo) {
        if (ConverterUtils.toDouble(goodsPrice) >= basePostageInfo.getFreePostage()) {
            gtTopFreight.setText("免配送费");
        } else {
            gtTopFreight.setText(basePostageInfo.getPostage() + "元");
            if (!Preconditions.isNullOrEmpty(basePostageInfo.getFreePostage())) {
                SHelper.vis(gtTopRightFreight);
                gtTopRightFreight.setText("(满" + CharacterUtils.roundByScale(basePostageInfo.getFreePostage()) + "元免邮)");
            }
        }
    }

    private void showShareGoodsPop() {
        if (shareGoodsPopUp == null) {
            shareGoodsPopUp = new ShareGoodsPopUp(this);
            shareGoodsPopUp.addGoodsDetailInfo(mGoodsDetailInfo);
            shareGoodsPopUp.showGoodsSharePopUp(goodsDetailTitle);
        } else {
            shareGoodsPopUp.showGoodsSharePopUp(goodsDetailTitle);
        }
    }

    /**
     * 绑定店铺商品列表
     */
    private void handleBindShopAdapter(BaseGoodsInfo shopGoodsInfo) {
        if (!Preconditions.isNullOrEmpty(shopGoodsInfo) && !Preconditions.isNullOrEmpty(shopGoodsInfo.get_embedded()) && !Preconditions.isNullOrEmpty(shopGoodsInfo.get_embedded().getContent())) {
            showShopInfo(mGoodsDetailInfo.getShop());
            LinearLayoutManager goods_layoutManager = new LinearLayoutManager(this);
            goods_layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            gtTopShopRv.setLayoutManager(goods_layoutManager);
            shopAdapter = new ShopDetailAdapter(shopGoodsInfo.get_embedded().getContent());
            shopAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
            gtTopShopRv.setAdapter(shopAdapter);
            shopAdapter.setOnItemClickListener((adapter, view, position) -> {
                if (!Preconditions.isNullOrEmpty(shopAdapter.getData().get(position).get_links())) {
                    Intent intent = new Intent(GoodsDetailActivity.this, GoodsDetailActivity.class);
                    intent.putExtra("url", shopAdapter.getData().get(position).get_links().getSelf().getHref());
                    intent.putExtra("goodFrom", goodFrom);
                    startActivity(intent);
                }
            });
        } else {
            SHelper.gone(gtTopShopLl);
        }
    }

    /**
     * 显示店铺信息
     *
     * @param shopBean
     */
    private void showShopInfo(GoodsDetailInfo.ShopBean shopBean) {
        SHelper.vis(gtTopShopLl);
        if (!Preconditions.isNullOrEmpty(shopBean)) {
            showShopType(shopBean.getShopTypeId());
            gtTopShopName.setText(shopBean.getName());
            BaseImageLoaderUtils.getInstance().loadRamdomImage(this, gtTopShopImg, shopBean.getLogo());
            gtTopShopNum.setText("在售商品" + shopBean.getGoodsTotals() + "件");
        }
    }

    /**
     * 添加购物车
     *
     * @param cartType
     */
    private void addCartPopWindow(int cartType) {
        if (!Preconditions.isNullOrEmpty(goodsDetailAddCartPop)) {
            goodsDetailAddCartPop.setAddCartCallBackListener(addCartCallBackListener);
            goodsDetailAddCartPop.setShowType(cartType);
            setPopAlphaParams();
        }
    }

    /**
     * 添加购物车
     */
    private GoodsDetailAddCartPop.AddCartCallBackListener addCartCallBackListener = new GoodsDetailAddCartPop.AddCartCallBackListener() {
        @Override
        public void addCart(String skuid, String num) {
            getAddCartTask(skuid, num);
        }
    };

    /**
     * 添加商品库存信息
     */
    private void addGoodsSkuInfo() {
        goodsDetailAddCartPop.addGoodsDetailInfo(mGoodsDetailInfo, skuInfos.getStock(), goodsPrice, discountPrice, skuInfos.getSpStr(), goodFrom);
    }

    /**
     * 透明背景设置
     */
    private void setPopAlphaParams() {
        goodsDetailAddCartPop.showAtLocation(goodsDetailBotLl, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        updateGoodsSkuProperties(goodSpStr);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.7f;
        goodsDetailAddCartPop.setOnDismissListener(() -> {
            params.alpha = 1f;
            getWindow().setAttributes(params);
        });
        getWindow().setAttributes(params);
    }

    /**
     * 获取添加购物车
     */
    private void getAddCartTask(String skuid, String num) {
        new AddCartTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                NewAddCartInfo newAddCartInfo = (NewAddCartInfo) o;
                if (!Preconditions.isNullOrEmpty(newAddCartInfo) && !Preconditions.isNullOrEmpty(newAddCartInfo.getShopId())) {
                    WpToast.l(GoodsDetailActivity.this, "加入购物车成功");
                    goodsDetailAddCartPop.dismiss();
                    loadCartNum();
                    ToCartRefreshEvent toCartRefreshEvent = new ToCartRefreshEvent();
                    toCartRefreshEvent.setShopCartRefresh(true);
                    RxBus.getInstance().post(toCartRefreshEvent);
                } else {
                    WpToast.l(GoodsDetailActivity.this, "加入购物车失败");
                }
            }
        }).execute(GoodsAddCartType.TYPE_1.getType() + "", mGoodsDetailInfo.getId(), num, mGoodsDetailInfo.getShop().getId(), skuid, url);
    }

    /**
     * 获取购物数量
     */
    private void loadCartNum() {
        if (BaseUserUtils.getIsLogin(this)) {
            new GetCartNunTask(this, o -> {
                NewAddCartInfo newCartListInfo = (NewAddCartInfo) o;
                if (!Preconditions.isNullOrEmpty(newCartListInfo)) {
                    handleCartNumShow(newCartListInfo.getTotalNum());
                }
            }).execute();
        }
    }

    /**
     * 显示购物车数量
     *
     * @param cartNum
     */
    private void handleCartNumShow(int cartNum) {
        if (!Preconditions.isNullOrEmpty(cartNum)) {
            qBadgeView.bindTarget(goodsDetailCart)
                    .setBadgeBackgroundColor(0xffdd2727)
                    .setBadgeGravity(Gravity.TOP | Gravity.END)
                    .setBadgePadding(3, true)
                    .setBadgeTextSize(5, true)
                    .setBadgeTextColor(0xffffffff)
                    .setExactMode(false)
                    .setBadgeNumber(cartNum);
        } else {
            qBadgeView.hide(true);
        }
    }

    /**
     * 观察者监听view高度
     */
    private void initListeners() {
        ViewTreeObserver vto = gtTopBanner.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                goodsDetailToolbar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                height = lp_banner.height;
                goodsDetailParent.setScrollViewListener(GoodsDetailActivity.this);
            }
        });
    }

    @Override
    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {   //设置标题的背景颜色
            goodsDetailToolbar.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
            goodsDetailTitle.setTextColor(Color.argb((int) 0, 255, 255, 255));
            goodsDetailFab.setVisibility(View.GONE);
        } else if (y > 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / height;
            float alpha = (255 * scale);
            goodsDetailTitle.setTextColor(Color.argb((int) alpha, 1, 24, 28));
            goodsDetailToolbar.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
            goodsDetailFab.setVisibility(View.GONE);
        } else {    //滑动到banner下面设置普通颜色
            goodsDetailToolbar.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
            goodsDetailToolbar.setAlpha(1);
            goodsDetailFab.setVisibility(View.VISIBLE);
            goodsDetailFab.setAlpha(0.75f);
        }
    }

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_GOODS_CART_REQUESR_CODE) {
            loadCartNum();
        }
    }
}
